package com.ftwj.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ftwj.entity.SysUser;
import com.ftwj.entity.UserBaseInfo;
import com.ftwj.mapper.*;
import com.ftwj.service.SysUserService;
import com.ftwj.vo.MenuVO;
import com.ftwj.vo.RoleVO;
import com.ftwj.vo.UserVO;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private UserBaseInfoMapper userBaseInfoMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysMenuListMapper sysMenuListMapper;


    @Override
    public List<UserVO> queryUsers(String userName, String sex ,String phoneNumber) {
        List<UserVO> result = sysUserMapper.queryUsersByConditions(userName, sex, phoneNumber);
        for (UserVO user : result) {
            user.setRole(sysUserRoleMapper.findRolesByUserId(user.getUserId()));
            // 遍历用户的所有角色
            for (RoleVO role : user.getRole()) {
                // 根据角色ID获取菜单信息
                List<MenuVO> menu = sysMenuListMapper.findMenusByRoleId(role.getRoleId());

                // 将菜单信息添加到用户对象中，这里创建一个新属性menu保存菜单列表
                user.setMenu(menu);
            }
        }
        return result;
    }

    @Override
    public void addUser(SysUser sysUser, UserBaseInfo baseInfo) {
        // 检查姓名、用户名和电话号码是否为空
        if (StringUtils.isBlank(sysUser.getNickName()) ||
                StringUtils.isBlank(sysUser.getPhoneNumber())||
                StringUtils.isBlank(baseInfo.getUserName())) {
            throw new IllegalArgumentException("姓名、用户名和电话号码均不能为空");
        }

        // 检查电话号码是否符合规范，这里以中国大陆手机号为例
        Pattern pattern = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9]))\\d{8}$+");
        Matcher matcher = pattern.matcher(sysUser.getPhoneNumber());
        if (!matcher.matches()) {
            throw new IllegalArgumentException("电话号码格式不正确，应为中国大陆手机号码");
        }

        // 检查电话号码是否重复
        List<SysUser> existingUsers = sysUserMapper.selectByPhone(sysUser.getPhoneNumber());
        if (!existingUsers.isEmpty()) {
            throw new IllegalArgumentException("电话号码已存在");
        }
        sysUser.setPassword("123456");
        sysUser.setCreateTime(DateTime.now());
        sysUser.setUpdateTime(DateTime.now());

        sysUserMapper.insert(sysUser);
        baseInfo.setUserId(sysUser.getId());
        baseInfo.setCreateTime(DateTime.now());
        baseInfo.setUpdateTime(DateTime.now());
        userBaseInfoMapper.insert(baseInfo);

    }

    @Override
    public void deleteUser(String id) {
        sysUserMapper.deleteById(id);

        // 使用 Map 存储条件参数
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("user_id", id);
        userBaseInfoMapper.deleteByMap(conditionMap);
        conditionMap.put("user_id", id);
        sysUserRoleMapper.deleteByMap(conditionMap);
    }
    @Override
    public void updateUser(SysUser sysUser, UserBaseInfo baseInfo) {
        // 更新sys_user表中的信息
        sysUser.setUpdateTime(DateTime.now());
        sysUserMapper.updateById(sysUser);

        // 更新user_base_info表中的信息
        baseInfo.setUpdateTime(DateTime.now());
        LambdaQueryWrapper<UserBaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBaseInfo::getUserId, baseInfo.getUserId()); // 设置更新条件，根据user_id
        userBaseInfoMapper.update(baseInfo, queryWrapper); // 执行更新操作
    }
    @Override
    public UserVO getUser(String id) {
        UserVO userById = sysUserMapper.getUserById(id);
        List<RoleVO> roles = sysUserRoleMapper.findRolesByUserId(userById.getUserId());

        // 使用Set来存储菜单，避免重复
        Map<String, MenuVO> menuMap = new HashMap<>();

        for (RoleVO role : roles) {
            List<MenuVO> menu = sysMenuListMapper.findMenusByRoleId(role.getRoleId());

            // 添加获取子菜单的方法，并加入到allMenus中
            for (MenuVO menuVo : menu) {
                if (!menuMap.containsKey(menuVo.getMenuId())) {
                    List<MenuVO> children = sysMenuListMapper.findChildrenByParentId(menuVo.getMenuId(), menuVo.getRoleId());
                    menuVo.setChildren(children);
                    menuMap.put(menuVo.getMenuId(), menuVo);
                }
            }
        }

        // 将Set转换回List
        List<MenuVO> menus = new ArrayList<>(menuMap.values());
        // 设置用户的角色和菜单
        userById.setRole(roles);
        userById.setMenu(menus);
        return userById;
    }


}
